package com.leesche.zcsp.node.web.controller.web.v2.account;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.PropKit;
import com.leesche.zcsp.node.utils.web.mathematical.MoneyCount;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubDevGiftStock;
import com.leesche.zcsp.node.web.model.PubDeviceBalance;
import com.leesche.zcsp.node.web.model.PubDeviceBalanceExport;
import com.leesche.zcsp.node.web.model.PubDevicePayDetailStatistics;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.vo.v2.AccountExportVo;
import com.leesche.zcsp.node.web.vo.v2.AccountSummaryVo;
import com.leesche.zcsp.node.web.vo.v2.PlaceDeviceListVo;
import com.leesche.zcsp.node.web.vo.v2.enums.AccountEnum;
import com.leesche.zcsp.node.web.vo.v2.enums.DeviceEnum;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.leesche.zcsp.node.utils.CsvUtil.createCsvFile;
import static com.leesche.zcsp.node.utils.UtilDate.*;

/**
 * Created by kaider on 2016/12/2.
 */
@Controller
@RequestMapping("/v2/account")
public class WebAccountController extends WebAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebAccountController.class);

    private static final String SHOW_VIEW = "web/v2/account/showView";

    private static String path = PropKit.use("rqcode.properties").get("destExportPath");

    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private PubDevicePayDetailStatisticsService statisticsService;
    @Autowired
    private PubDeviceBalanceService balanceService;
    @Autowired
    private PubDevGiftStockService giftStockService;
    @Autowired
    private PubDevicePayDetailService detailService;
    @Autowired
    private PubDeviceBalanceExportService exportService;
    @Autowired
    private NetService netService;

    /**
     * @return 总帐信息
     * @Title: showGeneralAccount(Long placeId, Long deviceId)
     * @Description: TODO(获取场地设备的总账目)
     * @author Jerry Chan
     * @date 2016/12/6 19:36
     */
    @RequestMapping(value = "ledgerView/{placeId}/{deviceId}/{deviceType}", method = RequestMethod.GET)
    public String showGeneralAccount(
            @PathVariable("placeId") Long placeId,
            @PathVariable("deviceId") Long deviceId,
            @PathVariable("deviceType") Integer deviceType,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            Model model
    ){
        AccountSummaryVo as = new AccountSummaryVo(deviceId);
        try {
            Long adminId = getAdminId();
            placeCondition.setAdminId(adminId);
            statisticsCondition.setUserId(adminId);
            statisticsCondition.setQueryAll(true);
            getDeviceType(model, deviceCondition);
            InfoDeviceDto dto = deviceService.findInfoDevice(deviceCondition);
            String stateName = DeviceEnum.parse(dto.getState()).getMessage();
            dto.setStateName(stateName);
            getPlacesDevices(model, placeCondition, deviceCondition);
            getQueryTime("ledgerView", model, null);

            //获取所有历史账目信息或所有结帐清零信息
            List<PubDevicePayDetailStatistics> statistics = statisticsService.findDeviceIncomeAccount(statisticsCondition);
            model.addAttribute("device", dto);
            if (statistics != null && statistics.size() > 0) {

                long billMoney = 0;
                long coinMoney = 0;
                long wechatMoney = 0;
                long alipayMoney = 0;

                for (PubDevicePayDetailStatistics statistic : statistics) {
                    //累计各面值纸币历史账目中的数量
                    as.setOneBalance(as.getOneBalance() + statistic.getOnebalance());
                    as.setFiveBalance(as.getFiveBalance() + statistic.getFivebalance());
                    as.setTenBalance(as.getTenBalance() + statistic.getTenbalance());
                    as.setTwentyBalance(as.getTwentyBalance() + statistic.getTwentybalance());
                    as.setFiftyBalance(as.getFiftyBalance() + statistic.getFiftybalance());
                    as.setHundredBalance(as.getHundredBalance() + statistic.getHundredbalance());
                    //累计非金钱收益统计
                    as.setRemotelyOutGameCoinQuantity(as.getRemotelyOutGameCoinQuantity() + statistic.getIntdata1());
                    as.setGameCoinQuantity(as.getGameCoinQuantity() + statistic.getGamecoinbalnce());
                    as.setGiftSellQuantity(as.getGiftSellQuantity() + statistic.getGiftbalance());
                    as.setOutGameCoinQuantity(as.getOutGameCoinQuantity() + statistic.getCoinbalance());
                    //累计收益统计
                    billMoney = billMoney + statistic.getBillmoney();
                    coinMoney = coinMoney + statistic.getCoinmoney();
                    wechatMoney = wechatMoney + statistic.getWechatmoney();
                    alipayMoney = alipayMoney + statistic.getAlipaymoney();
                }
                as.inventoryIncome(billMoney, coinMoney, wechatMoney, alipayMoney);
                //统计礼品库存
                QueryPubDevGiftStockCondition giftStockCondition = new QueryPubDevGiftStockCondition();
                giftStockCondition.setDeviceId(deviceId);
                PubDevGiftStock pubDevGiftStock = giftStockService.findGiftStockByCondition(giftStockCondition);
                as.setGiftstockQuantity(pubDevGiftStock == null ? 0 : pubDevGiftStock.getGiftqty());

            }else{
                as.toZero();
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            if (as == null) {
                as = new AccountSummaryVo();
                as.toZero();
            }
        }
        model.addAttribute("placeId", placeId);
        model.addAttribute("deviceId", deviceId);
        model.addAttribute("AccountSummary",as);
        model.addAttribute("deviceType",deviceType);
        model.addAttribute("view","2");
        return SHOW_VIEW;
    }


    /**
     * @return 具体清零结帐信息
     * @Title: showBalanceInfo(Long placeId, Long deviceId, Long balanceid)
     * @Description: TODO(获取场地设备的具体清零结帐信息)
     * @author Jerry Chan
     * @date 2016/12/6 19:36
     */
    @ResponseBody
    @RequestMapping(value = "showtozerobalance", method = RequestMethod.POST)
    public AccountSummaryVo showBalanceInfo(Long placeId, Long deviceId, Long balanceid) {
        AccountSummaryVo vo = null;
        try {
            vo = this.bindingAccountSummary(placeId, deviceId, balanceid);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            if (vo == null) {
                vo = new AccountSummaryVo();
                vo.toZero();
            }
        }
        return vo;
    }

    /**
     * 查询导出账目信息
     *
     * @param placeCondition
     * @param deviceCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/searchView", method = RequestMethod.GET)
    public String searchView(
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            Model model
    ){
        Long adminId = getAdminId();
        placeCondition.setAdminId(adminId);
        deviceCondition.setAdminId(adminId);
        getPlacesDevices(model, placeCondition, deviceCondition);
        model.addAttribute("placeId", 0);
        model.addAttribute("view",4);
        return SHOW_VIEW;
    }

    /**
     * 场地查询设备
     *
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchPlaceDevice", method = RequestMethod.POST)
    public Map<String, Object> searchPlaceDevice(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            Long adminId = getAdminId();
            deviceCondition.setAdminId(adminId);
            List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);
            return WebResult.success().put("data", deviceList).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 账目条件查询
     *
     * @param deviceCondition
     * @param giftStockCondition
     * @param statisticsCondition
     * @param placeCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Map<String, Object> search(
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            QueryPubPlaceCondition placeCondition
    ){
        AccountSummaryVo vo;
        InfoDeviceDto dto;
        try {
            Long adminId = getAdminId();
            statisticsCondition.setUserId(adminId);
            vo = searchParam(giftStockCondition,statisticsCondition);
            if(deviceCondition.getPlaceId()==null && deviceCondition.getDeviceId()==null ||
               deviceCondition.getPlaceId()==0 && deviceCondition.getDeviceId()==0){
                vo.setDeviceInfo("全场地全设备");
            }else{
                if(deviceCondition.getDeviceId()!=null&&deviceCondition.getDeviceId()!=0){
                    dto = deviceService.findInfoDevice(deviceCondition);
                    if(dto!=null){
                        dto.setStateName(DeviceEnum.parse(dto.getState()).getMessage());
                        String address = dto.getAddress()!=null?dto.getAddress():"";
                        String dtName = dto.getDtName()!=null?dto.getDtName():"";
                        String deviceName = dto.getDeviceName()!=null?dto.getDeviceName():"";
                        String deviceShortCode = dto.getDeviceShortCode()!=null?dto.getDeviceShortCode():"";
                        vo.setDeviceInfo(address+"  "+dtName+"  "+deviceName+"  "+deviceShortCode);
                    }
                }else{
                    PubPlaceDto placeDto = placeService.findByCondition(placeCondition);
                    vo.setDeviceInfo(placeDto.getAddress()+"全设备");
                }
            }
            return WebResult.success().put("AccountSummary", vo).toMap();
        } catch (NumberFormatException e) {
            LOGGER.error(e.getMessage(),e);
            vo = new AccountSummaryVo();
            vo.toZero();
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 导出
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public Map<String, Object> export(
            QueryPubDevicePayDetailCondition detailCondition
    ){
        try {
            Long adminId = getAdminId();
            detailCondition.setUserId(adminId);
            List<PubDevicePayDetailDto> detailDtos = detailService.findListsByCondition(detailCondition);
            if(detailDtos.size()!=0){
                List<Map<String,Object>> exportData = new ArrayList<Map<String,Object>>();
                for(PubDevicePayDetailDto dto : detailDtos){
                    AccountExportVo vo = new AccountExportVo();
                    contentReplace(vo,dto);
                    Map<String,Object> row = new LinkedHashMap<String,Object>();
                    row.put("title", vo.getTitle());
                    row.put("content", vo.getContent());
                    row.put("time", vo.getTime());
                    exportData.add(row);
                }

                LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("title", "支付方式");
                map.put("content", "交易内容");
                map.put("time", "交易时间");

                File file = createCsvFile(exportData,map,path,"LXJ-");
                if(file.exists() == false){
                    return WebResult.failure("生成失败!").toMap();
                }else{
                    //添加用户导出记录
                    PubDeviceBalanceExport balanceExport = new PubDeviceBalanceExport();
                    balanceExport.setUserId(adminId);
                    balanceExport.setPathUrl(file.getPath());
                    balanceExport.setExportName(file.getName());
                    balanceExport.setState(1);
                    balanceExport.setExportType(0);
                    balanceExport.setCreateTime(new Date());
                    exportService.insert(balanceExport);
                }
            }else{
                return WebResult.failure("暂无数据!").toMap();
            }
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 导出页面
     *
     * @param placeCondition
     * @param deviceCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/exportView", method = RequestMethod.GET)
    public String exportView(
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            QueryPubDeviceBalanceExportCondition exportCondition,
            Model model
    ){
        Long adminId = getAdminId();
        placeCondition.setAdminId(adminId);
        getPlacesDevices(model, placeCondition, deviceCondition);
        exportCondition.setAdminId(adminId);
        exportCondition.setExportType(0);
        List<PubDeviceBalanceExportDto> exportList = exportService.findListsByCondition(exportCondition);
        model.addAttribute("exportList",exportList);
        model.addAttribute("placeId", 0);
        return SHOW_VIEW;
    }

    /**
     * 导出下载
     * @return
     */
    @RequestMapping(value = "/exportDown/{exportId}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable("exportId")Long exportId) throws IOException{
        PubDeviceBalanceExport export = exportService.selectByPrimaryKey(exportId);
        File file = new File(path+export.getExportName());
        String dfileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        headers.setContentDispositionFormData("attachment", dfileName);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * 账目初始化界面(默认查询总账)
     *
     * @param placeCondition
     * @param deviceCondition
     * @param statisticsCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/{showView}", method = RequestMethod.GET)
    public String showView(
            @PathVariable("showView") String showView,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        Long adminId = getAdminId();
        placeCondition.setAdminId(adminId);
        deviceCondition.setAdminId(adminId);
        giftStockCondition.setAdminId(adminId);
        statisticsCondition.setUserId(adminId);
        getPlacesDevices(model, placeCondition, deviceCondition);
        getQueryTime(showView, model, statisticsCondition);
        getStatisticsDto(model, giftStockCondition, statisticsCondition);
        model.addAttribute("view", "1");
        return SHOW_VIEW;
    }

    /**
     * 查询场地账目
     *
     * @param placeId
     * @param placeCondition
     * @param deviceCondition
     * @param statisticsCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/{showView}/{placeId}", method = RequestMethod.GET)
    public String showPlaceView(
            @PathVariable("showView") String showView,
            @PathVariable("placeId") Long placeId,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        Long adminId = getAdminId();
        giftStockCondition.setAdminId(adminId);
        statisticsCondition.setUserId(adminId);
        statisticsCondition.setPlaceId(placeId);
        placeCondition.setAdminId(adminId);
        deviceCondition.setAdminId(adminId);
        getPlacesDevices(model, placeCondition, deviceCondition);
        getQueryTime(showView, model, statisticsCondition);
        getStatisticsDto(model, giftStockCondition, statisticsCondition);
        model.addAttribute("placeId", placeId);
        model.addAttribute("view", "1");
        return SHOW_VIEW;
    }

    /**
     * 某场地某设备账目
     *
     * @param placeId
     * @param deviceId
     * @param placeCondition
     * @param deviceCondition
     * @param statisticsCondition
     * @param model
     * @return
     */
    @RequestMapping(value = "/{showView}/{placeId}/{deviceId}/{status}", method = RequestMethod.GET)
    public String showPlaceDeviceView(
            @PathVariable("showView") String showView,
            @PathVariable("placeId") Long placeId,
            @PathVariable("deviceId") Long deviceId,
            @PathVariable("status") Integer status,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        Long adminId = getAdminId();
        placeCondition.setAdminId(adminId);
        giftStockCondition.setAdminId(adminId);
        statisticsCondition.setUserId(adminId);
        statisticsCondition.setPlaceId(placeId);
        statisticsCondition.setDeviceId(deviceId);
        InfoDeviceDto dto = deviceService.findInfoDevice(deviceCondition);
        String stateName = DeviceEnum.parse(dto.getState()).getMessage();
        dto.setStateName(stateName);
        getPlacesDevices(model, placeCondition, deviceCondition);
        getQueryTime(showView, model, statisticsCondition);
        getStatisticsDto(model, giftStockCondition, statisticsCondition);
        model.addAttribute("device", dto);
        model.addAttribute("placeId", placeId);
        model.addAttribute("deviceId", deviceId);
        model.addAttribute("deviceType",status);
        model.addAttribute("view", "2");
        return SHOW_VIEW;
    }

    /**
     * 按次数查询
     *
     * @return
     */
    @RequestMapping(value = "/{showView}/{placeId}/{deviceId}/{deviceType}/getAccount", method = RequestMethod.GET)
    public String getCountView(
            @PathVariable("showView") String showView,
            @PathVariable("placeId") Long placeId,
            @PathVariable("deviceId") Long deviceId,
            @PathVariable("deviceType") Integer deviceType,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            Model model
    ) {
        Long adminId = getAdminId();
        placeCondition.setAdminId(adminId);
        deviceCondition.setAdminId(adminId);
        getDeviceType(model, deviceCondition);
        InfoDeviceDto dto = deviceService.findInfoDevice(deviceCondition);
        String stateName = DeviceEnum.parse(dto.getState()).getMessage();
        dto.setStateName(stateName);
        getPlacesDevices(model, placeCondition, deviceCondition);
        AccountSummaryVo as = null;
        List asids = null;
        try {
            as = bindingAccountSummary(placeId, deviceId, null);
            statisticsCondition.setStime(as.getCreateDate());
            statisticsCondition.setEtime(as.getCreateDate());
            asids = obtainBalanceids(placeId, deviceId);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            if (as == null) {
                as = new AccountSummaryVo();
                as.toZero();
            }
            if (asids == null) {
                asids = new ArrayList();
            }
        }

        getQueryTime(showView, model, statisticsCondition);
        model.addAttribute("Accountids", asids);
        model.addAttribute("AccountSummary", as);
        model.addAttribute("device", dto);
        model.addAttribute("placeId", placeId);
        model.addAttribute("deviceId", deviceId);
        model.addAttribute("deviceType",deviceType);
        model.addAttribute("view", "3");
        return SHOW_VIEW;
    }

    /**
     * 查询用户所有场地所有设备
     *
     * @param placeCondition
     * @param deviceCondition
     * @return
     */
    private Model getPlacesDevices1(
            Model model,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition
    ) {
        List<PlaceDeviceListVo> placeDeviceListVo = new ArrayList<PlaceDeviceListVo>();
        placeCondition.setPlaceId(0L);
        placeCondition.setDeviceId(0L);
        deviceCondition.setPlaceId(0L);
        deviceCondition.setDeviceId(0L);

        try {
            List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
            for (PubPlaceDto dto : placeList) {
                PlaceDeviceListVo vo = new PlaceDeviceListVo();
                deviceCondition.setPlaceId(dto.getPlaceid());
                List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);
                //礼品机
                List<InfoDeviceDto> giftList = new ArrayList<InfoDeviceDto>();
                //兑币机
                List<InfoDeviceDto> currencyList = new ArrayList<InfoDeviceDto>();
                //娃娃机
                List<InfoDeviceDto> dollList = new ArrayList<InfoDeviceDto>();
                //礼品兑换机
                List<InfoDeviceDto> giftExchangeList = new ArrayList<InfoDeviceDto>();
                for (InfoDeviceDto dto1 : deviceList) {
                    switch (dto1.getDeviceTypeId().intValue()) {
                        case 1:
                            giftList.add(dto1);
                            break;
                        case 2:
                            currencyList.add(dto1);
                            break;
                        case 3:
                            dollList.add(dto1);
                            break;
                        case 4:
                            giftExchangeList.add(dto1);
                            break;
                        default:
                            break;
                    }
                }
                vo.setPlaceDto(dto);
                vo.setGiftList(giftList);
                vo.setCurrencyList(currencyList);
                vo.setDollList(dollList);
                vo.setGiftExchangeList(giftExchangeList);
                placeDeviceListVo.add(vo);
            }

            model.addAttribute("placeDeviceListVo", placeDeviceListVo);
            return model;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute("placeDeviceListVo", placeDeviceListVo);
            return model;
        }
    }

    /**
     * 查询用户所有场地所有设备
     * @param model
     * @param placeCondition
     * @param deviceCondition
     * @return
     */
    private Model getPlacesDevices(
            Model model,
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition
    ) {
        List<PlaceDeviceListVo> placeDeviceListVo = new ArrayList<PlaceDeviceListVo>();
        placeCondition.setPlaceId(0L);
        placeCondition.setDeviceId(0L);
        deviceCondition.setPlaceId(0L);
        deviceCondition.setDeviceId(0L);

        try {
            List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
            for (PubPlaceDto placeDto : placeList) {
                PlaceDeviceListVo vo = new PlaceDeviceListVo();
                deviceCondition.setPlaceId(placeDto.getPlaceid());
                List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

                //在线设备
                List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
                //离线设备
                List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
                //禁用设备
                List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
                //故障设备
                List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();

                if(deviceList.size()>0){
                    Map<String,String> onlineTemp = netService.isOnlineBatch(getDeviceNames(deviceList));
                    for(InfoDeviceDto dto : deviceList) {
                        if (onlineTemp.get(dto.getImme()) != null && onlineTemp.get(dto.getImme()).equalsIgnoreCase("ONLINE")) {
                            dto.setIsOnline(1);
                        } else {
                            dto.setIsOnline(2);
                        }
                        if (dto.getIsOnline().equals(1) && dto.getState().equals(2)) {
                            disabled.add(dto);
                        } else if (dto.getIsOnline().equals(1)) {
                            online.add(dto);
                        } else if (dto.getIsOnline().equals(2)) {
                            offline.add(dto);
                        } else {
                            fault.add(dto);
                        }
                    }
                }

                vo.setPlaceDto(placeDto);
                //在线
                vo.setGiftList(online);
                //离线
                vo.setCurrencyList(offline);
                //禁用
                vo.setDollList(disabled);
                //故障
                vo.setGiftExchangeList(fault);
                placeDeviceListVo.add(vo);
            }

            model.addAttribute("placeDeviceListVo", placeDeviceListVo);
            return model;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute("placeDeviceListVo", placeDeviceListVo);
            return model;
        }
    }

    /**
     * 获取账目信息
     *
     * @param model
     * @param statisticsCondition
     * @return
     */
    private Model getStatisticsDto(
            Model model,
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        AccountSummaryVo vo;
        try {
            Long adminId = getAdminId();
            statisticsCondition.setUserId(adminId);
            vo = searchParam(giftStockCondition,statisticsCondition);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(),e);
            vo = new AccountSummaryVo();
            vo.toZero();
        }
        model.addAttribute("AccountSummary", vo);
        return model;
    }

    /**
     * 获取选中设备的设备类型
     *
     * @param model
     * @param deviceCondition
     * @return
     */
    private Model getDeviceType(
            Model model,
            QueryPubDeviceCondition deviceCondition
    ) {
        InfoDeviceDto deviceDto = deviceService.findInfoDevice(deviceCondition);
        Long deviceTypeId = deviceDto.getDeviceTypeId();
        model.addAttribute("deviceType", deviceTypeId);
        return model;
    }

    /**
     * 设置周期获取的时间查询条件
     *
     * @param showView
     * @param statisticsCondition
     * @return
     */
    private Model getQueryTime(
            String showView,
            Model model,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        String sDate = getSimpleDate();
        String stime = "";
        String etime = "";
        AccountEnum accountEnum = AccountEnum.parse(showView);
        switch (accountEnum.getCode()) {
            case 1:
                statisticsCondition.setsDate(sDate);
                stime = sDate;
                etime = getWeek(sDate);
                break;
            case 2:
                stime = getCurrentMonday(sDate, 0);
                etime = getPreviousSunday(sDate, 0);
                statisticsCondition.setStime(stime);
                statisticsCondition.setEtime(etime);
                break;
            case 3:
                stime = getMinMonthDate(sDate, 0);
                etime = getMaxMonthDate(sDate, 0);
                statisticsCondition.setStime(stime);
                statisticsCondition.setEtime(etime);
                break;
            case 4:
                stime = getYesterday(sDate);
                etime = getYesterday(sDate);
                statisticsCondition.setStime(stime);
                statisticsCondition.setEtime(etime);
                etime = getWeek(etime);
                break;
            case 5:
                stime = getCurrentMonday(sDate, 1);
                etime = getPreviousSunday(sDate, 1);
                statisticsCondition.setStime(stime);
                statisticsCondition.setEtime(etime);
                break;
            case 6:
                stime = getMinMonthDate(sDate, 1);
                etime = getMaxMonthDate(sDate, 1);
                statisticsCondition.setStime(stime);
                statisticsCondition.setEtime(etime);
                break;
            case 7:
                if(statisticsCondition.getStime()!=null){
                    stime = statisticsCondition.getStime();
                    etime = "";
                }else{
                    stime = "该设备暂未结账";
                    etime = "";
                }
                break;
            case 8:
                stime = sDate;
                etime = getWeek(sDate);
                break;
            case 9:
                stime = statisticsCondition.getStime();
                etime = statisticsCondition.getEtime();
                break;
            default:
                break;
        }
        model.addAttribute("cur", accountEnum.getCode());
        model.addAttribute("stime", stime);
        model.addAttribute("etime", etime);
        return model;
    }

    /**
     * @param placeSerial   场地序号
     * @param deviceSerial  设备序号
     * @param balanceSerial 结帐序号(为空表示获取最近一次清零结帐信息)
     * @return 账目概要VO类
     * @Title: bindingAccountSummary(Long placeSerial, Long deviceSerial, Long balanceSerial)
     * @Description: TODO(绑定账目概要VO类)
     * @author Jerry Chan
     * @date 2016/12/6 19:35
     */
    private AccountSummaryVo bindingAccountSummary(Long placeSerial, Long deviceSerial, Long balanceSerial) throws Exception {
        Long adminId = getAdminId();
        AccountSummaryVo as = new AccountSummaryVo(deviceSerial);
        InfoDeviceDto dto = null;
        QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
        QueryPubDeviceCondition deviceCondition = new QueryPubDeviceCondition();
        condition.setDeviceid(deviceSerial);
        condition.setPlaceid(placeSerial);
        condition.setUserid(adminId);
        deviceCondition.setDeviceId(deviceSerial);
        deviceCondition.setPlaceId(placeSerial);
        deviceCondition.setAdminId(adminId);
        if ((balanceSerial != null) && (balanceSerial.longValue() > 0)) {
            condition.setBalanceid(balanceSerial);
        }

        PubDeviceBalance balance = this.balanceService.findBalanceByDeviceid(condition);
        if (balance != null) {
            as.setBalanceid(balance.getBalanceid());
            as.inventoryCashQuantity(balance.getOnebalance().longValue(), balance.getFilebalance().longValue(), balance.getTenbalance().longValue(), balance.getTwentybalance().longValue(), balance.getFiftybalance().longValue(), balance.getHundredbalance().longValue());
            Long billbalance = Long.valueOf(balance.getOnebalance().longValue() * 1 + balance.getFilebalance().longValue() * 5 + balance.getTenbalance().longValue() * 10 + balance.getTwentybalance().longValue() * 20 + balance.getFiftybalance().longValue() * 50 + balance.getHundredbalance().longValue() * 100);
            as.inventoryIncome(billbalance.longValue(), balance.getCoinbalance().longValue(), balance.getWechatbalance().longValue(), balance.getAlipaybalance().longValue());
            as.setCreateDate(timeToStr(balance.getBalancetime()));

            QueryPubDevGiftStockCondition giftStockCondition = new QueryPubDevGiftStockCondition();
            giftStockCondition.setDeviceId(deviceSerial);
            PubDevGiftStock pubDevGiftStock = this.giftStockService.findGiftStockByCondition(giftStockCondition);
            as.inventoryNotIncome(Integer.valueOf(Integer.parseInt(String.valueOf(balance.getGamecoinbu()))), balance.getGamecoin(), balance.getGift(), balance.getGamecoinout(), Integer.valueOf(pubDevGiftStock == null ? 0 : pubDevGiftStock.getGiftqty().intValue()));

            dto = deviceService.findInfoDevice(deviceCondition);
            if(dto!=null){
                String address = dto.getAddress()!=null?dto.getAddress():"";
                String dtName = dto.getDtName()!=null?dto.getDtName():"";
                String deviceName = dto.getDeviceName()!=null?dto.getDeviceName():"";
                String deviceShortCode = dto.getDeviceShortCode()!=null?dto.getDeviceShortCode():"";
                as.setDeviceInfo(address+"  "+dtName+"  "+deviceName+"  "+deviceShortCode);
            }

        } else {
            as.toZero();
        }
        return as;
    }

    /**
     * @param placeSerial  场地序号
     * @param deviceSerial 设备序号
     * @return 清零结帐信息ID集合
     * @Title: obtainBalanceids(Long placeSerial, Long deviceSerial)
     * @Description: TODO(获取场地设备的清零结帐信息ID集合)
     * @author Jerry Chan
     * @date 2016/12/6 19:17
     */
    private List<Long> obtainBalanceids(Long placeSerial, Long deviceSerial) throws Exception {
        Long adminId = getAdminId();
        QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
        condition.setDeviceid(deviceSerial);
        condition.setPlaceid(placeSerial);
        condition.setUserid(adminId);
        List<PubDeviceBalance> deviceBalances = this.balanceService.findBalanceidsByDeviceid(condition);

        List balanceids = null;

        if ((deviceBalances != null) && (deviceBalances.size() > 0)) {
            balanceids = new ArrayList();

            for (PubDeviceBalance deviceBalance : deviceBalances) {
                balanceids.add(deviceBalance.getBalanceid());
            }
        }

        return balanceids;
    }

    /**
     * 条件查询返回数据
     * @param statisticsCondition
     * @return
     */
    private AccountSummaryVo searchParam(
            QueryPubDevGiftStockCondition giftStockCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) throws NumberFormatException{
        AccountSummaryVo vo = new AccountSummaryVo();
        if(statisticsCondition.getsDate()==null && statisticsCondition.getStime().equals("") && statisticsCondition.getEtime().equals("")){
            statisticsCondition.setsDate(getSimpleDate());
        }
        PubDevicePayDetailStatisticsDto statisticsDto = statisticsService.findByCondition(statisticsCondition);
        Integer giftCount = giftStockService.getGiftCount(giftStockCondition);
        if(statisticsCondition.getsDate()==null && statisticsCondition.getStime().equals("") && statisticsCondition.getEtime().equals("")){
            vo.setCreateDate(getSimpleDate()+"  ~  "+getWeek(getSimpleDate()));
        }else if(statisticsCondition.getsDate()!=null){
            vo.setCreateDate(getSimpleDate()+"  ~  "+getWeek(getSimpleDate()));
        }else{
            vo.setCreateDate(statisticsCondition.getStime()+"  ~  "+statisticsCondition.getEtime());
        }

        if (statisticsDto != null) {
            statisticsDto.setGiftCount(giftCount!=null?giftCount:0);
            //现金数量
            vo.inventoryCashQuantity(
                    statisticsDto.getSumOnebalance(),
                    statisticsDto.getSumFivebalance(),
                    statisticsDto.getSumTenbalance(),
                    statisticsDto.getSumTwentybalance(),
                    statisticsDto.getSumFiftybalance(),
                    statisticsDto.getSumHundredbalance());

            //统计收益
            vo.inventoryIncome(statisticsDto.getBillmoney(),
                    statisticsDto.getCoinmoney(),
                    statisticsDto.getWechatmoney(),
                    statisticsDto.getAlipaymoney());

            //统计非费用收益
            vo.inventoryNotIncome(
                    statisticsDto.getIntdata1(),
                    statisticsDto.getGamecoinbalnce(),
                    statisticsDto.getGiftbalance(),
                    statisticsDto.getCoinbalance(),
                    statisticsDto.getGiftCount()
            );
        }else{
            vo.toZero();
        }
        return vo;
    }

    /**
     * 导出信息转换
     *
     * @param dto
     */
    private AccountExportVo contentReplace(AccountExportVo vo,PubDevicePayDetailDto dto){
        Integer payType = dto.getPaytype();
        vo.setTitle(Constants.AppDetailTitle.getText(dto.getPaytype()));
        vo.setTime(timeToStr(dto.getUploadtime()));
        int flag;
        if(payType==1){
            flag=1;
        }else if(payType==2 || payType==3){
            flag=2;
        }else if(payType>3 && payType<10){
            flag = 3;
        }else if(payType>9){
            flag = 4;
        }else{
            flag = 5;
        }
        String content;
        switch (flag){
            //硬币
            case 1:
                content = "￥"+Constants.DECIMAL_FORMAT.format(dto.getCoin());
                break;
            //在线支付
            case 2:
                content = "￥"+Constants.DECIMAL_FORMAT.format(MoneyCount.percentageCount(dto.getCoin().longValue(), Constants.percentage));
                break;
            //纸币
            case 3:
                Integer cash = Constants.CashType.getCachType(payType);
                Integer quantity = dto.getCoin();
                content = cash+"元"+quantity+"张 - ￥"+Constants.DECIMAL_FORMAT.format(MoneyCount.worthCount(cash, quantity).doubleValue());
                break;
            //其他
            case 4:
                content = dto.getCoin()+"个";
                break;
            default:
                content = "其他异常";
                break;
        }
        vo.setContent(content);
        return vo;
    }

    private List<String> getDeviceNames(List<InfoDeviceDto> lists) {
        List<String> deviceNames = new ArrayList<String>();
        if (lists != null) {
            for (InfoDeviceDto infoDeviceDto : lists) {
                deviceNames.add(infoDeviceDto.getImme());
            }
        }
        return deviceNames;
    }
}
